package com.dpying.mgtv.autoplay.autoplay;

import android.app.*;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import com.android.volley.*;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;


public class ForegroundService extends Service {
    private final String TAG = "Play Service";
    public static final String CHANNEL_ID="foregroudServiceChannel";

    private final int NOTIFICATIONID = (int) System.currentTimeMillis();
    private RemoteViews remoteViews;
    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mbuilder;

    private String ADBManagerServerIP;
    private String did;

    private RequestQueue queue;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //启动一个通知后台
    private void initNotificationViews(){
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        remoteViews = new RemoteViews(getPackageName(), R.layout.foreground_service);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_ID,
                    NotificationManager.IMPORTANCE_LOW);
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }

        remoteViews.setTextViewText(R.id.label, "AUTOPLAY正在运行..");

        //点击返回应用, 构建任务堆栈
        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

        mbuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
        mbuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setOngoing(true)
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                .setContent(remoteViews)
                .setSound(null)
                .setContentIntent(resultPendingIntent);

        Notification notification = mbuilder.build();
        startForeground(NOTIFICATIONID, notification);
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "后台服务创建完成");
        queue = Volley.newRequestQueue(this);
        initNotificationViews();
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        Log.i("Service", "onDestroy");
        this.queue.cancelAll(ForegroundService.class);
        super.onDestroy();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.ADBManagerServerIP = intent.getStringExtra("ip");
        this.did = intent.getStringExtra("id");
        Log.d(TAG, String.format("后台服务启动, IP: %s, did: %s",this.ADBManagerServerIP,  this.did ));

        //TODO
        // requestPlayTask() => openMGTV() => any time gone => report() => callADBCloseMgtvAPP()
        requestPlayTask();
        // START_NOT_STICKY 因内存不足杀死了该进程，稍后有足够内存时，不重启服务
        // START_STICKY 因内存不足杀死该进程时，稍后有足够内存时，重启服务
        // START_REDELIVER_INTENT 因内存不足杀死该进程时，稍后有足够内存时，重启服务，并按原来的参数数据调用onStartCommand
        return START_REDELIVER_INTENT;
    }

    private void openMGTV(final String cid,final String vid, final int playTime)
    {
        String mgtvURI = String.format(
                "imgotv://player?clipId=%s&plId=0&videoId=%s&start_time=0&from=mphone&pos=2",
                cid,
                vid
        );
        Log.d(TAG, String.format("任务内容 cid: %s, vid: %s, time: %d", cid, vid, playTime));
        Intent mgtv = new Intent("android.intent.action.VIEW", Uri.parse(mgtvURI));
        mgtv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mgtv);

        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {
                        callADBCloseMgtvAPP(cid, vid, playTime);
                    }
                },
                1000 * playTime);

    }

    private void callADBCloseMgtvAPP(String cid, String vid, int playTime){
        Log.d(TAG, "任务完成");
        report(did, cid, vid, playTime);

        String url = String.format("%s?did=%s", ADBManagerServerIP, did);
        Log.d(TAG, "开始请求关闭MGTV");
        //定义一个字符串型请求队列，需要传递4个参数分别是：url, 请求的方式(get, post..)，响应成功的处理函数匿名对象， 相应出错时候的处理函数匿名对象
        StringRequest stringRequest = new StringRequest(
                Request.Method.GET,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "完成关闭请求，等待重新运行Service");
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Play Service", error.toString());

                    }
        });
        stringRequest.setTag(ForegroundService.class);
        //添加到请求队列中，默认就开始了网络请求
        queue.add(stringRequest);
    }

    //上报
    private void report(final String did,final String cid,final String vid,final int playTime){

        String url = String.format("%s?did=%s&cid=%s&vid=%s&play=%d",
                getResources().getString(R.string.api_report),
                did,
                cid,
                vid,
                playTime);
        Log.d(TAG, String.format("开始上报数据,上报地址: %s", url));
        StringRequest stringRequest = new StringRequest(
                Request.Method.GET,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Play Service", "上报完成");
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Play Service", "上报发生错误");
                    }
                });
        stringRequest.setTag(ForegroundService.class);
        //添加到请求队列中，默认就开始了网络请求
        queue.add(stringRequest);
    }

    //获取播放任务
    private void requestPlayTask(){
        Log.d(TAG, "开始请求任务内容");
        JsonObjectRequest request =  new JsonObjectRequest(Request.Method.GET,
                getResources().getString(R.string.api_video_task),
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            String cid = response.getString("cid");
                            String vid = response.getString("vid");
                            int playTime = response.getInt("time");
                            openMGTV(cid, vid, playTime);

                        }catch (JSONException e){
                            Log.e("Play Service", e.toString());
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Service", error.toString());
                    }
                });
        request.setTag(ForegroundService.class);
        queue.add(request);
    }

}
